/*
 * @Author: Leo.wang wanglizhigs@163.com
 * @Date: 2024-06-04 22:12:02
 * @LastEditors: Leo.wang wanglizhigs@163.com
 * @LastEditTime: 2024-06-16 16:34:42
 * @FilePath: /chat-ai-plus/src/api/chat.api.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { request, METHOD } from "@/service/http.service";
import { createParser } from 'eventsource-parser'
import { TextDecoder } from 'text-encoding'
import { session, local } from "@/service/storage.service";
const { VITE_STORAGE_TOKEN, VITE_API_URL } = import.meta.env;


export function getTopicList(params = {}) {
  return request({
    url: "/api/gptRoom",
    method: METHOD.GET,
    params
  })
}

export function createTopic(data = {}) {
  return request({
    url: "/api/gptRoom",
    method: METHOD.POST,
    data
  })
}


export function updateTopic() {
  return request({
    url: "/api/gptRoom",
    method: METHOD.PUT,
  })
}

export function removeTopic(ids = []) {
  return request({
    url: "/api/gptRoom",
    method: METHOD.DELETE,
    data: ids,
  })
}

export function collectTopic(id) {
  return request({
    url: `/api/gptRoom/updateArchive/${id}`,
    method: METHOD.GET,
  })
}

export function unCollectTopic(id) {
  return request({
    url: `/api/gptRoom/cancelArchive/${id}`,
    method: METHOD.GET,
  })
}

export function getConversationsById(params = {}) {
  return request({
    url: "/api/gptMsg",
    method: METHOD.GET,
    params
  })
}




export function generateImage(data = {}) {
  return request({
    url: '/api/creatImage',
    method: 'POST',
    data,
  })
}


export function generateText(data = {}) {
  return request({
    url: '/api/chat',
    method: 'POST',
    data,
  })
}




export function sendMessage(data = {}, onMessage, onError) {
  const abortController = new AbortController() || {}
  const token = local.get(VITE_STORAGE_TOKEN);
  const sseParser = createParser(async (event) => {

    if (event.type === 'event') {
      onMessage && onMessage(event.data !== "[DONE]" ? JSON.parse(event.data) : undefined)
    }
  })
  // #ifdef MP_WEIXIN



  const req = wx.request({
    url: `${VITE_API_URL}/api/chat`,
    method: 'POST',
    data,
    enableChunked: true,
    header: {
      Authorization: `Bearer ${token}`,
    },
    success(res) {
      if (res.statusCode > 299) {
        onError && onError(res.data)
      }
    },
  })
  req.onChunkReceived((chunk) => {
    const uint8Array = new Uint8Array(chunk.data)
    const str = new TextDecoder().decode(uint8Array)
    sseParser.feed(str)
  })
  // #endif

  // #ifdef WEB
  fetch(`${VITE_API_URL}/api/chat`, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
    signal: abortController.signal,
  }).then(async (response) => {
    if (response.status > 299) {
      onError && onError(response)
      return
    }
    const reader = response.body.getReader()
    while (true) {
      const { done, value } = await reader.read()
      if (done) {
        break
      }
      const str = new TextDecoder().decode(value)
      sseParser.feed(str)
    }
  })
  // #endif

}



export function uploadFile(data = {}) {
  const token = local.get(VITE_STORAGE_TOKEN);
  return new Promise((resolve, reject) => {

    uni.uploadFile({
      url: `${VITE_API_URL}/api/upload`,
      ...data,
      header: {
        Authorization: `Bearer ${token}`,
      },
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}



